﻿using System;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
using Arch.System;
using Microsoft.Reporting.WinForms;
using Pharmacy.Data;
using Pharmacy.Entities;
using Pharmacy.Settings.BusinessLayer;
using Pharmacy.Windows.Forms.App_Code;
using Pharmacy.Windows.Forms.App_Code.DSPrescriptionSlipTableAdapters;

namespace Pharmacy
{
    /// <summary>
    /// 
    /// </summary>
    public static class Utilities
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="createP"></param>
        public static void CreateDBF(Prescription createP)
        {
            string connectionString =
                String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=dBase IV",
                              ServiceFacade.SettingsHelper.CmsDirectory);

            var connection = new OleDbConnection(connectionString);
            OleDbCommand command = connection.CreateCommand();
            string tableName = "PR" + createP.PatientCode;
            if (File.Exists(ServiceFacade.SettingsHelper.CmsDirectory + "\\" + tableName + ".dbf"))
                File.Delete(ServiceFacade.SettingsHelper.CmsDirectory + "\\" + tableName + ".dbf");
            connection.Open();
            command.CommandText = " CREATE TABLE " + tableName + " (PAT_FILCOD VarChar," +
                                  "PAT_CODTYP VarChar,PAT_NAME VarChar,PAT_F_NAME VarChar," +
                                  "PAT_M_INIT VarChar,DATE_VISIT smalldatetime,PHAR_NBER VarChar," +
                                  "PHAR_CODE VarChar,PHAR_NAME VarChar,PHAR_TYPE VarChar,PHAR_QANT VarChar," +
                                  "HEALTHLINE Bit,PHAR_PRICE Double,PHAR_PAY Double,PHAR_HL Double,PHAR_X Double," +
                                  "SALE_PRICE Double,PHAR_UNIT VarChar,SELL_UNIT VarChar,PHAR_MS Double,MED_SCHM Bit," +
                                  "CASH_NAME VarChar,AREA VarChar,FLAG_PULL Bit)";
            command.ExecuteNonQuery();
            for (int i = 0; i < createP.PrescriptionDetailCollection.Count; i++)
            {
                PrescriptionDetail detail = createP.PrescriptionDetailCollection[i];
                command = connection.CreateCommand();
                string cmdText = "INSERT INTO " + tableName +
                                 "(PAT_FILCOD,DATE_VISIT,PHAR_NBER,PHAR_CODE,PHAR_NAME,PHAR_PRICE," +
                                 "PHAR_PAY,PHAR_X,SALE_PRICE,SELL_UNIT,CASH_NAME,AREA,PHAR_HL) " +
                                 "VALUES (@PAT_FILCOD,@DATE_VISIT,@PHAR_NBER,@PHAR_CODE,@PHAR_NAME," +
                                 "@PHAR_PRICE,@PHAR_PAY,@PHAR_X,@SALE_PRICE,@SELL_UNIT,@CASH_NAME,@AREA,@PHAR_HL)";
                command.CommandText = cmdText;
                command.Parameters.AddWithValue("@PAT_FILCOD", createP.PatientCode);
                command.Parameters.AddWithValue("@DATE_VISIT", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
                command.Parameters.AddWithValue("@PHAR_NBER", i);
                command.Parameters.AddWithValue("@PHAR_CODE", detail.DrugId);
                command.Parameters.AddWithValue("@PHAR_NAME", detail.DrugName);
                command.Parameters.AddWithValue("@PHAR_PRICE", detail.AmountPrice - detail.CoveredPlan);
                command.Parameters.AddWithValue("@PHAR_PAY", detail.AmountPrice - detail.CoveredPlan);
                command.Parameters.AddWithValue("@PHAR_X", detail.Quantity);
                command.Parameters.AddWithValue("@SALE_PRICE", detail.UnitPrice - detail.CoveredPlan / detail.Quantity);
                command.Parameters.AddWithValue("@SELL_UNIT", detail.Unit);
                command.Parameters.AddWithValue("@CASH_NAME", createP.SalesPerson);
                command.Parameters.AddWithValue("@AREA", createP.PrescriptionId);
                command.Parameters.AddWithValue("@PHAR_HL", detail.IsControlDrug ? 1 : 0);
                command.ExecuteNonQuery();
            }
            connection.Close();
        }

        //In Stock
        /// <summary>
        /// 
        /// </summary>
        /// <param name="createP"></param>
        /// <param name="transaction"></param>
        /// <param name="voidReason"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public static bool VoidPrescription(Prescription createP, TransactionManager transaction, string voidReason,
                                            string remark)
        {
            try
            {
                foreach (PrescriptionDetail detail in createP.PrescriptionDetailCollection)
                {
                    Stock objStock = DataRepository.StockProvider.GetByDrugIdExpDateBatchLot(transaction, detail.DrugId,
                                                                                             detail.ExpDate,
                                                                                             detail.BatchLot);
                    if (objStock == null)
                    {
                        objStock = new Stock
                                       {
                                           DrugId = detail.DrugId,
                                           ExpDate = detail.ExpDate,
                                           BatchLot = detail.BatchLot,
                                           UnitPrice = detail.CostPrice,
                                           Quantity = detail.Quantity
                                       };
                    }
                    else
                    {
                        objStock.UnitPrice = (objStock.UnitPrice * objStock.Quantity + detail.Quantity * detail.CostPrice) /
                                             (objStock.Quantity + detail.Quantity);
                        objStock.Quantity += detail.Quantity;
                    }
                    DataRepository.StockProvider.Save(transaction, objStock);
                }
                createP.IsVoid = true;
                var objPrescriptionVoid = new PrescriptionVoid
                                              {
                                                  PrescriptionId = createP.PrescriptionId,
                                                  VoidDate = DateTime.Now,
                                                  VoidReason = voidReason,
                                                  Remark = remark,
                                                  VoidPerson = Program.GlobalUser.UserId
                                              };
                DataRepository.PrescriptionVoidProvider.Insert(transaction, objPrescriptionVoid);
                DataRepository.PrescriptionProvider.Update(transaction, createP);
                string tableName = "PR" + createP.PatientCode;
                if (File.Exists(ServiceFacade.SettingsHelper.CmsDirectory + "\\" + tableName + ".dbf"))
                    File.Delete(ServiceFacade.SettingsHelper.CmsDirectory + "\\" + tableName + ".dbf");
            }
            catch (Exception ex)
            {
                ShowException(ex);
                return false;
            }
            return true;
        }

        private static void ShowException(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="printP"></param>
        /// <param name="reportViewer"></param>
        /// <param name="copy"></param>
        /// <param name="isVoid"></param>
        /// <param name="voidReason"></param>
        /// <param name="canPrint"></param>
        /// <returns></returns>
        public static bool PreviewDeliveryNote(Prescription printP, ReportViewer reportViewer, string copy, bool isVoid,
                                               string voidReason, ref bool canPrint)
        {
            DataRepository.PrescriptionProvider.DeepLoad(printP, true, DeepLoadType.IncludeChildren, typeof(WebUser));
            var dtPatient = new DSPrescriptionSlip.PatientDataTable();
            DSPrescriptionSlip.PatientRow dtPatientRow = dtPatient.NewPatientRow();
            dtPatientRow.Serial = printP.PrescriptionId;
            dtPatientRow.Name = printP.PatientName;
            dtPatientRow.PatientID = printP.PatientCode;
            dtPatientRow.CompanyAddress = ServiceFacade.SettingsHelper.DnCompanyAddress;
            dtPatientRow.BrandName = ServiceFacade.SettingsHelper.DnBrandName;
            dtPatientRow.TaxCode = ServiceFacade.SettingsHelper.TaxCode;
            dtPatientRow.PayableAmount = printP.PayableAmount;
            dtPatientRow.CoveredPlan = printP.CoveredTotal;
            if (isVoid)
            {
                dtPatientRow.TitleEng = ServiceFacade.SettingsHelper.DnVoidTitleEng;
                dtPatientRow.TitleVN = ServiceFacade.SettingsHelper.DnVoidTitleVn;
                dtPatientRow.VoidReason = voidReason;
            }
            else
            {
                dtPatientRow.TitleEng = ServiceFacade.SettingsHelper.DnTitleEng;
                dtPatientRow.TitleVN = ServiceFacade.SettingsHelper.DnTitleVn;
            }
            var dtDrugs = new DSPrescriptionSlip.DetailsDataTable();
            var adt = new DetailsADT { ClearBeforeFill = true };
            adt.Connection = new SqlConnection(DataRepository.ConnectionStrings["Pharmacy.Forms.Properties.Settings.CMSConnectionString"].ConnectionString);
            adt.Fill(dtDrugs, printP.PrescriptionId);
            bool printControlDrug = false;
            //Print only Delivery Note if not void
            if (!isVoid)
            {
                var dtFilterDrugs = new DSPrescriptionSlip.DetailsDataTable();
                decimal total = 0, coveredTotal = 0;
                foreach (DSPrescriptionSlip.DetailsRow detailsRow in dtDrugs)
                {
                    if (detailsRow.IsControlDrug)
                        printControlDrug = true;
                    else
                    {
                        dtFilterDrugs.ImportRow(detailsRow);
                        total += detailsRow.UnitPrice * detailsRow.Quantity;
                        coveredTotal += detailsRow.CoveredPlan;
                    }
                }
                if (dtFilterDrugs.Rows.Count > 0)
                {
                    dtPatientRow.Copy = copy;
                    dtPatientRow.CoveredPlan = coveredTotal;
                    dtPatientRow.PayableAmount = total - coveredTotal;
                    decimal vat = dtPatientRow.PayableAmount * ServiceFacade.SettingsHelper.VATPercent / (decimal)100.0;
                    dtPatientRow.VAT = vat;
                    dtPatientRow.SubTotal = total;
                    dtPatientRow.Total = dtPatientRow.PayableAmount + vat;
                    dtPatientRow.Company = printP.Address;
                    dtPatientRow.SalesPerson = printP.SalesPersonSource.Name;
                    dtPatientRow.DeliveryDate = printP.DeliveryDate;
                    if (printP.DateOfBirth != null) dtPatientRow.DateOfBirth = printP.DateOfBirth.Value;
                    dtPatientRow.AmountInWordsEng = ReadAmountEN.ReadDecimalNumber(dtPatientRow.Total);
                    //dtPatientRow.AmountInWordsVnd = ReadAmountVN.DocTienBangChu(dtPatientRow.Total, " VND");
                    dtPatient.Rows.Add(dtPatientRow);

                    reportViewer.Reset();
                    reportViewer.ProcessingMode = ProcessingMode.Local;
                    reportViewer.LocalReport.ReportEmbeddedResource = "Pharmacy.Windows.Forms.App_Code.ControlDrug.rdlc";
                    reportViewer.LocalReport.EnableExternalImages = true;
                    reportViewer.LocalReport.DataSources.Clear();
                    reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DSPrescriptionSlip_Patient",
                                                                                  dtPatient));
                    reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DSPrescriptionSlip_Details",
                                                                                  dtFilterDrugs));
                    reportViewer.RefreshReport();
                }
                else
                {
                    canPrint = false;
                }
            }
            //Print all detail for void
            else
            {
                dtPatientRow.Copy = copy;
                dtPatientRow.VAT = printP.Vat;
                dtPatientRow.SubTotal = printP.Amount;
                dtPatientRow.CoveredPlan = printP.CoveredTotal;
                dtPatientRow.PayableAmount = printP.PayableAmount;
                dtPatientRow.Total = printP.TotalAmount;
                dtPatientRow.Company = printP.Address;
                dtPatientRow.SalesPerson = printP.SalesPersonSource.Name;
                dtPatientRow.DeliveryDate = printP.DeliveryDate;
                if (printP.DateOfBirth != null) dtPatientRow.DateOfBirth = printP.DateOfBirth.Value;
                dtPatientRow.AmountInWordsEng = ReadAmountEN.ReadDecimalNumber(printP.TotalAmount);
                //dtPatientRow.AmountInWordsVnd = ReadAmountVN.DocTienBangChu(printP.TotalAmount, " VND");
                dtPatient.Rows.Add(dtPatientRow);

                reportViewer.Reset();
                reportViewer.ProcessingMode = ProcessingMode.Local;
                reportViewer.LocalReport.ReportEmbeddedResource = "Pharmacy.Windows.Forms.App_Code.ControlDrug.rdlc";
                reportViewer.LocalReport.EnableExternalImages = true;
                reportViewer.LocalReport.DataSources.Clear();
                reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DSPrescriptionSlip_Patient", dtPatient));
                reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DSPrescriptionSlip_Details", dtDrugs));
                reportViewer.RefreshReport();
            }
            return printControlDrug;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="printP"></param>
        /// <param name="reportViewer"></param>
        /// <param name="copy"></param>
        /// <param name="isVoid"></param>
        /// <param name="voidReason"></param>
        public static void PreviewControlDrug(Prescription printP, ReportViewer reportViewer, string copy, bool isVoid,
                                              string voidReason)
        {
            DataRepository.PrescriptionProvider.DeepLoad(printP, true, DeepLoadType.IncludeChildren, typeof(WebUser));
            var dtPatient = new DSPrescriptionSlip.PatientDataTable();
            DSPrescriptionSlip.PatientRow dtPatientRow = dtPatient.NewPatientRow();
            dtPatientRow.Serial = printP.PrescriptionId;
            dtPatientRow.Name = printP.PatientName;
            dtPatientRow.PatientID = printP.PatientCode;
            dtPatientRow.CompanyAddress = ServiceFacade.SettingsHelper.SOSCompanyName;
            dtPatientRow.BrandName = ServiceFacade.SettingsHelper.SOSClinicAddress;
            dtPatientRow.TaxCode = ServiceFacade.SettingsHelper.TaxCode;
            if (isVoid)
            {
                dtPatientRow.TitleEng = ServiceFacade.SettingsHelper.DnVoidTitleEng;
                dtPatientRow.TitleVN = ServiceFacade.SettingsHelper.DnVoidTitleVn;
                dtPatientRow.VoidReason = voidReason;
            }
            else
            {
                dtPatientRow.TitleEng = ServiceFacade.SettingsHelper.DnTitleEng;
                dtPatientRow.TitleVN = ServiceFacade.SettingsHelper.DnTitleVn;
            }

            var dtDrugs = new DSPrescriptionSlip.DetailsDataTable();
            var adt = new DetailsADT { ClearBeforeFill = true };
            adt.Connection = new SqlConnection(DataRepository.ConnectionStrings["Pharmacy.Forms.Properties.Settings.CMSConnectionString"].ConnectionString);
            adt.Fill(dtDrugs, printP.PrescriptionId);

            var dtFilterDrugs = new DSPrescriptionSlip.DetailsDataTable();
            decimal total = 0;
            foreach (DSPrescriptionSlip.DetailsRow detailsRow in dtDrugs)
            {
                if (detailsRow.IsControlDrug)
                {
                    dtFilterDrugs.ImportRow(detailsRow);
                    total += detailsRow.UnitPrice * detailsRow.Quantity;
                }
            }

            dtPatientRow.Copy = copy;
            decimal vat = total * ServiceFacade.SettingsHelper.VATPercent / (decimal)100.0;
            dtPatientRow.VAT = vat;
            dtPatientRow.SubTotal = total;
            dtPatientRow.Total = total + vat;
            dtPatientRow.Company = printP.Address;
            dtPatientRow.SalesPerson = printP.SalesPersonSource.Name;
            dtPatientRow.DeliveryDate = printP.DeliveryDate;
            if (printP.DateOfBirth != null) dtPatientRow.DateOfBirth = printP.DateOfBirth.Value;
            dtPatientRow.AmountInWordsEng = ReadAmountEN.ReadDecimalNumber(dtPatientRow.Total);
            //dtPatientRow.AmountInWordsVnd = ReadAmountVN.DocTienBangChu(dtPatientRow.Total, " VND");
            dtPatient.Rows.Add(dtPatientRow);

            reportViewer.Reset();
            reportViewer.ProcessingMode = ProcessingMode.Local;
            reportViewer.LocalReport.ReportEmbeddedResource = "Pharmacy.Windows.Forms.App_Code.ControlDrug.rdlc";
            reportViewer.LocalReport.EnableExternalImages = true;
            reportViewer.LocalReport.DataSources.Clear();
            reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DSPrescriptionSlip_Patient", dtPatient));
            reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DSPrescriptionSlip_Details", dtFilterDrugs));
            reportViewer.RefreshReport();
        }
    }
}